var uid = 0;

// visibility filters
var filters = {
    all: function (todos) {
      return todos
    },
    active: function (todos) {
      return todos.filter(todo => !todo.completed)
    },
    completed: function (todos) {
      return todos.filter(todo => todo.completed)
    }
  }

// app Vue instance
var app = new Vue({
    // app initial state
    data: {
        todos: [],
        newTodo: '',
        editedTodo: null,
        visibility: 'all'
    },

    computed: {
        filteredTodos: function () {
          return filters[this.visibility](this.todos)
        },
        remaining: function () {
          return filters.active(this.todos).length
        },
        pluralize: function () {
          return this.remaining === 1 ? 'item' : 'items'
        }
      },

    methods: {
        addTodo: function () {
            var value = this.newTodo && this.newTodo.trim()  //trim:移除空格
            if (!value) return

            this.todos.push({
                id: uid++,
                title: value,
                completed: false
            })
            this.newTodo = ''
        },

        removeTodo: function (todo) {
            this.todos.splice(this.todos.indexOf(todo), 1)
        },

        editTodo: function (todo) {
            this.beforeEditCache = todo.title
            this.editedTodo = todo
        },

        doneEdit: function (todo) {
            if (!this.editedTodo) {
                return
            }
            this.editedTodo = null
            todo.title = todo.title.trim()
            if (!todo.title) {
                this.removeTodo(todo)
            }
        },

        cancelEdit: function (todo) {
            this.editedTodo = null
            todo.title = this.beforeEditCache
        },

        removeCompleted: function () {
            this.todos = filters.active(this.todos)
          },
      
        showAll () {
            this.visibility = 'all'
        },
        showActive () {
            this.visibility = 'active'
        },
        showCompleted () {
            this.visibility = 'completed'
        }
    },

    
})

// mount
app.$mount('.todoapp')
